<template>
  <view class="order-detail">
    <view class="info-panel order-process">
      <text class="order-process__title"> 订单流程 </text>
      <steps-bar :step-list="processMap" :cur-idx="curProcess" />
    </view>
    <view class="info-panel base-info">
      <text class="base-info-panel__title"> 基本信息 </text>
      <up-cell-group :border="false">
        <up-cell title="联系人" :value="orderDetail.contacts" />
        <up-cell title="联系方式" :value="orderDetail.phone" />
        <up-cell title="邮箱" :value="orderDetail.email" />
        <up-cell
          v-if="orderDetail.type === '1'"
          title="身份证"
          :value="orderDetail.certNumber"
        />
        <up-cell
          v-if="orderDetail.type === '0'"
          title="统一社会信用代码"
          :value="orderDetail.certNumber"
        />
      </up-cell-group>
    </view>

    <view class="info-panel house-info">
      <text class="info-panel__title"> 房源信息 </text>
      <up-cell-group :border="false">
        <up-cell title="户型" :value="orderDetail.smallHouseTypeName" />
        <up-cell title="数量" :value="`${orderDetail.number} 套`" />
        <up-cell title="预订金" :value="`${orderDetail.money} 元`" />
        <up-cell
          title="预订总金额"
          :value="`${orderDetail.money * orderDetail.number} 元`"
        />
      </up-cell-group>
    </view>
    <view
      class="info-panel refuse-info"
      v-if="refusedStatus.includes(orderDetail.checkStatus)"
    >
      <text class="info-panel__title" style="color: red"> 审核不通过原因 </text>
      <view class="info-panel__text">
        {{ orderDetail?.approvalOpinion }}
      </view>
    </view>
    <view
      v-if="!lockedStatus.includes(orderDetail.checkStatus)"
      :class="['fixed-btn']"
    >
      <up-button
        v-if="!refundStatus.includes(orderDetail.checkStatus)"
        class="fixed-btn-cancel"
        plain
        shape="circle"
        text="取消预订"
        type="warning"
        iconColor="linear-gradient(to right, #FF934C, #FC686F)"
        @tap="handleCancelReserveBtnClick"
      />
      <up-button
        v-if="!refundStatus.includes(orderDetail.checkStatus)"
        class="fixed-btn-pay"
        shape="circle"
        text="去支付"
        color="linear-gradient(to right, #FF934C, #FC686F)"
        :disabled="!showPayBtnStatus.includes(orderDetail.checkStatus)"
        @tap="handlePayBtnClick"
      />
      <up-button
        v-if="refundStatus.includes(orderDetail.checkStatus)"
        class="fixed-btn-pay"
        shape="circle"
        text="退款"
        color="linear-gradient(to right, #FF934C, #FC686F)"
        @tap="handleRefundBtnClick"
      />
    </view>

    <view class="modal-cancel">
      <up-modal
        :show="cancelReserveModalDisabled"
        :confirmColor="'#5590F6'"
        title="操作确认"
        content="是否取消预订"
        showCancelButton
        closeOnClickOverlay
        @close="handleCancelModalClose"
        @cancel="handleCancelReserveModalCancelBtnClick"
        @confirm="handleCancelReserveModalConfirmBtnClick"
      />
    </view>

    <view class="modal-refund">
      <up-modal
        :show="refundModalDisabled"
        :confirmColor="'#5590F6'"
        title="操作确认"
        :content="refundModalText"
        showCancelButton
        closeOnClickOverlay
        @close="handleRefundModalClose"
        @cancel="handleRefundModalCancelBtnClick"
        @confirm="handleRefundModalConfirmBtnClick"
      />
    </view>

    <view class="popup-pay">
      <up-popup
        :show="payPopupDisabled"
        closeOnClickOverlay
        @close="handlePayPopupClose"
      >
        <view class="popup-pay__title"> 收银台 </view>
        <view class="popup-pay__desc">
          <view class="popup-pay__desc-title">
            {{ orderDetail.smallHouseTypeName }}
          </view>
          <view class="popup-pay__desc-detail">
            <text class="popup-pay__desc-detail-label"> 应付金额 </text>
            <text class="popup-pay__desc-detail-value">
              ¥ {{ orderDetail.money * orderDetail.number }}元
            </text>
          </view>
        </view>
        <up-cell-group :border="false">
          <up-cell v-for="(item, idx) in payWayList" :key="idx">
            <template #title>
              <view class="u-slot-title">
                <image class="pay-way__img" :src="item.payWayPrefixIconUrl" />
              </view>
              <view class="pay-way__name">
                <text class="pay-way__name-title">{{ item.payWayName }}</text>
                <text class="pay-way__name-desc">{{ item.desc }}</text>
              </view>
            </template>
            <template #value>
              <image
                v-if="item.isChecked"
                class="pay-way__img is-checked"
                :src="isCheckedImgUrl"
              />
              <image
                v-else
                class="pay-way__img"
                :src="notCheckedImgUrl"
                @tap="handleCheckedPayWay(item)"
              />
            </template>
          </up-cell>
        </up-cell-group>

        <view class="popup-pay__btn-group">
          <up-button
            class="btn__pay"
            shape="circle"
            :text="`立即支付¥ ${orderDetail.money * orderDetail.number} 元`"
            :disabled="payWayList.every((way) => !way.isChecked)"
            color="linear-gradient(to right, #FF934C, #FC686F)"
            @tap="handlePayForWithWayBtnClick"
          />
          <up-button
            class="btn__later-pay"
            plain
            shape="circle"
            text="稍后支付"
            type="warning"
            iconColor="linear-gradient(to right, #FF934C, #FC686F)"
            @tap="handleLaterPayBtnClick"
          />
        </view>
      </up-popup>
    </view>
  </view>
</template>
<script setup>
import { ref, reactive, inject, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  getCurrentPagesTotal,
  getUrlParamsInH5,
  getUrlParamsInWeixin,
} from "@/utils/utils";
import {
  cancelOrderApi,
  getOrderDetailApi,
  getOrderPayDataApi,
  userCancelPayApi,
  userRefundApi,
} from "@/package_kuafu_apartment/pages/api/order";
import stepsBar from "../../components/steps-bar";
import { customNav } from "@/utils/customNav";

const lockedStatus = ["1", "4", "5", "6", "7", "8", "9", "10"];
const refusedStatus = ["1", "11", "13"];
const refundStatus = ["3", "11"];
const showPayBtnStatus = ["2", "13"];
const statusCodeMap = [
  {
    code: "0",
    status: "审核中",
  },
  {
    code: "1",
    status: "未通过",
  },
  {
    code: "2",
    status: "待支付",
  },
  {
    code: "3",
    status: "已支付",
  },
  {
    code: "4",
    status: "已撤销",
  },
  {
    code: "5",
    status: "部分退款",
  },
  {
    code: "6",
    status: "全额退款",
  },
  {
    code: "7",
    status: "转线下",
  },
  {
    code: "8",
    status: "已签约",
  },
  {
    code: "9",
    status: "对公转账支付审核中",
  },
  {
    code: "10",
    status: "对公转账退款审核中",
  },
  {
    code: "11",
    status: "对公转账退款审核不通过",
  },
  {
    code: "12",
    status: "支付中",
  },
  {
    code: "13",
    status: "对公转账支付审核不通过",
  },
];
let processMap = reactive([
  {
    text: "审核中",
    isEnd: false,
  },
  {
    text: "待支付",
    isEnd: false,
  },
  {
    text: "已支付",
    isEnd: false,
  },
]);

const orderType = ref("");
const curOrderId = ref("");
const curProcess = ref(0);
const orderDetail = ref({});
const orderLastProcessDetail = ref({});
const getOrderDetailData = async () => {
  const res = await getOrderDetailApi(curOrderId.value);
  const { code, data } = res;
  const { checkStatus } = data[0];
  if (code === 200) {
    orderDetail.value = data[0];
    orderLastProcessDetail.value = data?.[1];
    let findStatusCode;
    switch (checkStatus) {
      case "0":
      case "3":
        curProcess.value = checkStatus;
        break;
      case "1":
      case "11":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = processMap.slice(0, 1).concat([
          {
            text: findStatusCode.status,
            isEnd: true,
            isError: true,
          },
        ]);
        break;
      case "2":
        curProcess.value = 1;
        break;
      case "4":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = [
          { text: findStatusCode.status, isEnd: true, isError: true },
        ];
        break;
      case "5":
      case "6":
      case "7":
      case "8":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = processMap.concat([
          { text: findStatusCode.status, isEnd: true },
        ]);
        curProcess.value = processMap.length;
        break;
      case "9":
      case "10":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = processMap.concat([
          { text: findStatusCode.status, isEnd: true },
        ]);
        curProcess.value = processMap.length;
        break;
      case "12":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = [{ text: findStatusCode.status, isEnd: true }];
        break;
      case "13":
        findStatusCode = statusCodeMap.find(
          (item) => item.code === checkStatus
        );
        processMap = processMap.concat([
          { text: findStatusCode.status, isEnd: true, isError: true },
        ]);
        curProcess.value = processMap.length;
        break;
    }
  }
};

const cancelReserveModalDisabled = ref(false); /* 取消预订弹窗显示控制 */
const handleCancelReserveBtnClick = () => {
  cancelReserveModalDisabled.value = true;
};
const handleCancelModalClose = () => {
  cancelReserveModalDisabled.value = false;
};
const handleCancelReserveModalCancelBtnClick = () => {
  cancelReserveModalDisabled.value = false;
};

const handleCancelReserveModalConfirmBtnClick = async () => {
  const res = await cancelOrderApi(orderDetail.value.reserveId);
  const { code, data } = res;
  if (code === 200) {
    uni.showToast({
      title: "取消预订成功",
      duration: 2000,
      success: () => {
        cancelReserveModalDisabled.value = false;
        getOrderDetailData();
      },
    });
  }
};

const refundModalDisabled = ref(false); /* 退款弹窗显示控制 */
const refundModalText = ref("");
const handleRefundBtnClick = () => {
  refundModalDisabled.value = true;
  const curStatus = orderDetail.value.checkStatus;
  if (
    curStatus === "11" ||
    (orderLastProcessDetail.value.checkStatus === "9" && curStatus === "3")
  ) {
    refundModalText.value = `温馨提示: 若取消预订,请联系我们线下办理退款。
        联系电话: 0851-84766886/18985546686`;
  } else {
    refundModalText.value = "确认要申请退款?";
  }
};
const handleRefundModalClose = () => {
  refundModalDisabled.value = false;
};
const handleRefundModalCancelBtnClick = () => {
  refundModalDisabled.value = false;
};
const handleRefundModalConfirmBtnClick = () => {
  refund();
};
const refund = async () => {
  const params = {
    reason: "退款",
    id: orderDetail.value.reserveId,
  };
  const res = await userRefundApi(params);
  const { code } = res;
  if (code === 200) {
    await uni.showToast({
      title: "退款申请提交成功",
      duration: 3000,
      success: () => {
        refundModalDisabled.value = false;
        getOrderDetailData();
      },
    });
  }
};

const payPopupDisabled = ref(false);
const handlePayBtnClick = () => {
  if (!showPayBtnStatus.includes(orderDetail.value.checkStatus)) return;
  payPopupDisabled.value = true;
};
const handlePayPopupClose = () => {
  payPopupDisabled.value = false;
};
const imgUrlPrefix = inject("baseImgUrl");
const isCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103545102组 4@2x.png`;
const notCheckedImgUrl = `${imgUrlPrefix}2024-04-26/1714103688260椭圆 586 拷贝@2x.png`;
const payWayList = ref([
  {
    payWayName: "微信支付",
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101755578weixin@2x.png`,
    desc: "亿万用户的选择，更快更安全",
    isChecked: false,
  },
  {
    payWayName: "对公账号",
    payWayPrefixIconUrl: `${imgUrlPrefix}2024-04-26/1714101841808gongduigongzhuanzhang@2x.png`,
    desc: "获取对公支付账号，支付成功后请上传凭证审核",
    isChecked: false,
  },
]);
const handleCheckedPayWay = (item) => {
  payWayList.value.forEach((way) => {
    way.isChecked = way.payWayName === item.payWayName;
  });
};
const handleLaterPayBtnClick = () => {
  payPopupDisabled.value = false;
  payWayList.value.forEach((way) => {
    way.isChecked = false;
  });
};
const handlePayForWithWayBtnClick = () => {
  if (payWayList.value.every((way) => !way.isChecked)) return;
  const way = payWayList.value.find((way) => way.isChecked).payWayName;
  switch (way) {
    case "微信支付":
      let payType = "";
      // #ifndef MP-WEIXIN
      payType = "1";
      // #endif
      // #ifdef MP-WEIXIN
      payType = "0";
      // #endif
      getOrderPayData(payType);
      break;
    case "对公账号":
      const orderId = orderDetail.value.reserveId;
      customNav(
        `public-transfer?orderId=${orderId}&price=${
          orderDetail.value.money * orderDetail.value.number
        }&payName=房屋订金`
      );
      break;
  }
};
const getOrderPayData = async (type) => {
  const params = {
    id: orderDetail.value.reserveId,
    payType: type,
  };
  const res = await getOrderPayDataApi(params);
  const { code, data } = res;
  if (code === 200) {
    // #ifndef MP-WEIXIN
    weChatAppPay(data);
    // #endif
    // #ifdef MP-WEIXIN
    toPay(data);
    // #endif
  }
};
const toPay = (payData) => {
  uni.requestPayment({
    provider: "wxpay",
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
      uni.showToast({
        title: "支付成功",
        duration: 2000,
        success: () => {
          payPopupDisabled.value = false;
          getOrderDetailData();
        },
      });
    },
    fail: function (err) {
      userCancelPayApi(orderDetail.value.reserveId).then((res) => {
        console.log("success" + JSON.stringify(res.data));
      });
      console.log("fail:" + JSON.stringify(err));
    },
  });
};
const weChatAppPay = (payData) => {
  let params = {
    partnerId: payData.partnerId,
    prepayId: payData.prepayId,
    nonceStr: payData.nonceStr,
    timeStamp: payData.timeStamp,
    sign: payData.paySign,
  };
  window.mobile.jsCallPayWx(JSON.stringify(params));
};

onLoad(() => {
  /* #ifdef MP-WEIXIN */
  curOrderId.value = getUrlParamsInWeixin()?.id;
  orderType.value = getUrlParamsInWeixin()?.orderType;
  /* #endif */

  /* #ifndef MP-WEIXIN */
  curOrderId.value = getUrlParamsInH5()?.id;
  orderType.value = getUrlParamsInH5()?.orderType;
  /* #endif */

  getOrderDetailData();
});
</script>
<style scoped lang=less>
@import "./style/order-detail";
</style>
